<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/11/9  19:27
 */
namespace app\api\logic;
use app\api\BaseModel;

class Index extends  BaseModel{

    /**
     * 分类
     */
    public function category(){
        $type=isset($this->requestData['type'])?$this->requestData['type']:0;
        $category= db('category_shop');
        $res = $category ->field('id,name,image')->where("status=1")->order("sort desc")->select();
        foreach($res as &$v){
            $v['image']=IMG_PATH.$v['image'];
        }
        if($type==0) {
            $data = array_chunk($res, 10);
            return $data;
        }
        return $res;
    }

    /**
     * 轮播图
     */
    public function banner(){
        $banner = db('banner');
        $ban = $banner ->where("status=1 and type=0")->select();
        foreach($ban as &$v){
            $v['pic']=IMG_PATH.$v['pic'];
        }
        return $ban;
    }
    /**
     * 今日爆款
     */
    public function home()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $lat = isset($this->requestData['lat'])?trim($this->requestData['lat']): '23.13098';
        $lng = isset($this->requestData['lng'])?trim($this->requestData['lng']):  '113.403873';

        //以当前用户经纬度为中心,查询50000米内的其他用户
        $y = 50000 / 110852; //纬度的范围
        $x = 50000 / (111320*cos($lat)); //经度的范围
        $a = $lat-$y;
        $b = $lat+$y;
        $c = $lng-$x;
        $d = $lng+$x;
        $condition=' s.status=1 and s.ishome=1';
        $condition.=' and  lat >='.$a.' and lat <= '.$b.' and  lng <='.$c.' and lng >= '.$d.'  ';
        $list=db('shop')
            ->alias('s')
            ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount,s.commission")
            ->join("category_shop c","c.id=s.cid")
            ->where($condition)
            ->select();
        $db_order=db("order");
        $distant=[];
        foreach($list as $k=> $val){
            $radLat1=deg2rad($lat);
            $radLat2 = deg2rad($val['lat']);
            $a = $radLat1 - $radLat2;
            $b =deg2rad($lng) - deg2rad($val['lng']);
            $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
            $meter=$s*6378137.0;
            $distant[]=$meter;
            if($meter>1000){
                $meter=number_format($meter/1000,2).'km';
            }else{
                $meter=number_format($meter,2).'m';
            }
            $list[$k]['distant']=$meter;
            if($val['headimage']) {
                $list[$k]['headimage'] = IMG_PATH . $val['headimage'];
            }
            $or['o.shop_id'] = $val['id'];
            $or['o.status'] = ['in',['1','2','3','-2']];
            $or['o.pay_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
            $order_num = $db_order->alias('o')->join('order_goods og','og.order_id=o.id')->where($or)->sum('og.goods_num');
            $list[$k]['ordernum'] =$order_num;
            if($val['discount']) {
                $list[$k]['discount'] = unserialize($val['discount']);
            }
            if(empty($val['commission'])){
                $member_config_value = db('config')->where(['id'=>'6'])->value('value');
                $list[$k]['commission'] = $member_config_value;
            }
        }
        //return $discount;
        array_multisort($distant, SORT_ASC, $list);
        $shop=array_chunk($list,$size);
        $count=count($shop);
        if($p>$count ||$p<1) return array("message"=>'页码有误');
        $data['list']=$shop[$p-1];
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }
    /**
     * 关于我们
     */
    public function contract(){
        $id=2;
        $contract = db('contract');
        $data = $contract->field("content") ->where("id='$id'")->find();
        $data['content']=htmlspecialchars_decode($data['content']);
        return $data;
    }

    /**
     * 联系我们
     */
    public function contact(){
        $id=2;
        $contract = db('contract');
        $data = $contract->field("image,mobile") ->where("id='$id'")->find();
        $data['image']=IMG_PATH.$data['image'];
        return $data;
    }

    public function recommend()
    {
        $activity=db("activity")->select();
        foreach($activity as &$v){
            $v['image'] = IMG_PATH . $v['image'];
        }
        return $activity;
    }
    
    public function getPosition(){
        $getIp=request()->ip();
        $ak = BAIDU_AK;
        $content = file_get_contents("http://api.map.baidu.com/location/ip?ak={$ak}&ip={$getIp}&coor=bd09ll");
        $json = json_decode($content,true);
     
        if($json['status'] == 0){
            $position['lat'] = $json['content']['point']['y'];
            $position['lng'] =  $json['content']['point']['x'];

        }else{
            $position['lat'] = '23.122816';
            $position['lng'] = '113.398927';
        }
      var_dump($position);

    }
    /**
     * 搜索返回是商品还是店铺
     */
    public function search()
    {
        $lat  =isset($this->requestData['lat'])?trim($this->requestData['lat']): '23.13098';
        $lng =isset($this->requestData['lng'])?trim($this->requestData['lng']):  '113.403873';
        if(!isset($this->requestData['search']) || empty($this->requestData['search'])){
            return array("message"=>'请输入要搜索的内容');
        };
        $y = 5000000 / 110852; //纬度的范围
        $x = 5000000 / (111320*cos($lat)); //经度的范围
        $a = $lat-$y;
        $b = $lat+$y;
        $c = $lng-$x;
        $d = $lng+$x;
        $condition=' s.status=1';
        $condition.=' and  lat >='.$a.' and lat <= '.$b.' and  lng <='.$c.' and lng >= '.$d.'  ';
        $condition2 =' and shopname="'.$this->requestData['search'].'"';
        $list=db('shop')
            ->alias('s')
            ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount")
            ->join("category_shop c","c.id=s.cid")
            ->where($condition.$condition2)
            ->select();
        if($list) {
            if(count($list)>1){
                foreach($list as $li){
                    $li['discount']=unserialize($li['discount']);
                }
            }else{
                $discount=unserialize($list[0]['discount']);
                $list[0]['discount']=$discount;
            }
            //$discount=json_decode(unserialize($list['discount']),true);
            //var_dump($discount);
            //$list['s.discount']=$discount;
            if(isset($list[0]['headiamge'])){
                $list[0]['headimage'] = IMG_PATH . $list[0]['headimage'];
            }
            $data['list']=$list;
            $data['type']=0;
        }else{
            $data['type']=1;
        }
        return $data;
    }

    public function searchgoods()
    {
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $sort = isset($this->requestData['sort']) ? $this->requestData['sort'] : '0';
        $dw['name'] = array("like", '%' . $this->requestData['search'] . '%');
        $goods = db('goods')
            ->field("id,shop_id,name,price,oldprice,image")
            ->where($dw)
            ->select();

        $lat = isset($this->requestData['lat']) ? trim($this->requestData['lat']) : '23.13098';
        $lng = isset($this->requestData['lng']) ? trim($this->requestData['lng']) : '113.403873';
        $y = 5000000 / 110852; //纬度的范围
        $x = 5000000 / (111320 * cos($lat)); //经度的范围
        $a = $lat - $y;
        $b = $lat + $y;
        $c = $lng - $x;
        $d = $lng + $x;
        $shop_ids = array_column($goods, 'shop_id');
        $condition = ' s.status=1';
        $condition .= ' and  lat >=' . $a . ' and lat <= ' . $b . ' and  lng <=' . $c . ' and lng >= ' . $d . '  ';
        $data['list']=array();
        $data['count']=0;
        if ($shop_ids) {
            $condition3 = ' and s.id in (' . implode(",", $shop_ids) . ')';
            $list = db('shop')
                ->alias('s')
                ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname")
                ->join("category_shop c", "c.id=s.cid")
                ->where($condition . $condition3)
                ->select();

            if ($list) {
                $db_order = db("order");
                foreach ($list as &$v) {
                    foreach ($goods as &$d) {
                        $where['o.shop_id'] = $d['shop_id'];
                        $where['o.status'] = '3';
                        $where['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                        $where['og.goods_id'] = $d['id'];
                        $d['order_num'] = $db_order->alias("o")
                            ->join("order_goods og", "og.order_id=o.id")
                            ->where($where)
                            ->count();
                        if ($v['id'] == $d['shop_id']) {
                            if(!empty($d['image'])){
                                $d['image'] = IMG_PATH . $d['image'];
                            }
                            $v['goods'][] = $d;
                        }
                    }
                    $or['shop_id'] = $v['id'];
                    $or['status'] = '3';
                    $or['finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                    $num[] = $db_order->where($or)->count();
                    if ($v['headimage']) {
                        $v['headimage'] = IMG_PATH . $v['headimage'];
                    }
                    $radLat1 = deg2rad($lat);
                    $radLat2 = deg2rad($v['lat']);
                    $a = $radLat1 - $radLat2;
                    $b = deg2rad($lng) - deg2rad($v['lng']);
                    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                    $meter = $s * 6378137.0;
                    $distant[] = $meter;
                    $ids[] = $v['id'];
                    if ($meter > 1000) {
                        $meter = number_format($meter / 1000, 2) . 'km';
                    } else {
                        $meter = number_format($meter, 2) . 'm';
                    }

                    $v['distant'] = $meter;
                }
                if ($sort == 0) {
                    array_multisort($ids, SORT_ASC, $list);
                } elseif ($sort == 1) {
                    array_multisort($num, SORT_ASC, $list);
                } elseif ($sort == 2) {
                    array_multisort($distant, SORT_ASC, $list);
                }
                $shop = array_chunk($list, $size);
                $count = count($shop);
                if ($p > $count || $p < 1) return array("message" => '页码有误');
                $data['type'] = 1;
                $data['list'] = $shop[$p - 1];
                $data['count'] = count($list);;
            }
        }
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }

    public function menu()
    {
        $goods_id=db("activity_list")->where("aid=2")->column("goods_id");
        $goods_ids=array_unique($goods_id);
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $sort = isset($this->requestData['sort']) ? $this->requestData['sort'] : '0';
        if(!empty($goods_ids)) {
            if(isset( $this->requestData['search'])) {
                $dw['name'] = array("like", '%' . $this->requestData['search'] . '%');
            }
            $dw['status']=1;
            $dw['id']=array("in",implode(",", $goods_ids));
            $goods = db('goods')
                ->field("id,shop_id,name,price,oldprice,image")
                ->where($dw)
                ->select();
            $lat = isset($this->requestData['lat']) ? trim($this->requestData['lat']) : '23.13098';
            $lng = isset($this->requestData['lng']) ? trim($this->requestData['lng']) : '113.403873';
            $y = 5000 / 110852; //纬度的范围
            $x = 5000 / (111320 * cos($lat)); //经度的范围
            $a = $lat - $y;
            $b = $lat + $y;
            $c = $lng - $x;
            $d = $lng + $x;
            $condition = ' s.status=1';
            $condition .= ' and  lat >=' . $a . ' and lat <= ' . $b . ' and  lng <=' . $c . ' and lng >= ' . $d . '  ';
            $data['list']=array();
            $data['count']=0;
            $shop_ids = array_column($goods, 'shop_id');
            if ($shop_ids) {
                $condition3 = ' and s.id in (' . implode(",", $shop_ids) . ')';
                $list = db('shop')
                    ->alias('s')
                    ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname")
                    ->join("category_shop c", "c.id=s.cid")
                    ->where($condition . $condition3)
                    ->select();

                if ($list) {
                    $db_order = db("order");
                    foreach ($list as &$v) {
                        foreach ($goods as &$d) {
                            $where['o.shop_id'] = $d['shop_id'];
                            $where['o.status'] = '3';
                            $where['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                            $where['og.goods_id'] = $d['id'];
                            $d['order_num'] = $db_order->alias("o")
                                ->join("order_goods og", "og.order_id=o.id")
                                ->where($where)
                                ->count();
                            $d['image'] = IMG_PATH . $d['image'];
                            if ($v['id'] == $d['shop_id']) {
                                $v['goods'][] = $d;
                            }
                        }
                        $or['shop_id'] = $v['id'];
                        $or['status'] = '3';
                        $or['finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                        $num[] = $db_order->where($or)->count();
                        if ($v['headimage']) {
                            $v['headimage'] = IMG_PATH . $v['headimage'];
                        }
                        $radLat1 = deg2rad($lat);
                        $radLat2 = deg2rad($v['lat']);
                        $a = $radLat1 - $radLat2;
                        $b = deg2rad($lng) - deg2rad($v['lng']);
                        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                        $meter = $s * 6378137.0;
                        $distant[] = $meter;
                        $ids[] = $v['id'];
                        if ($meter > 1000) {
                            $meter = number_format($meter / 1000, 2) . 'km';
                        } else {
                            $meter = number_format($meter, 2) . 'm';
                        }

                        $v['distant'] = $meter;
                    }
                    if ($sort == 0) {
                        array_multisort($ids, SORT_ASC, $list);
                    } elseif ($sort == 1) {
                        array_multisort($num, SORT_ASC, $list);
                    } elseif ($sort == 2) {
                        array_multisort($distant, SORT_ASC, $list);
                    }
                    $shop = array_chunk($list, $size);
                    $count = count($shop);
                    if ($p > $count || $p < 1) return array("message" => '页码有误');
                    $data['type'] = 1;
                    $data['list'] = $shop[$p - 1];
                    $data['count'] = count($list);;
                }
            }
            $data['page_num']=$p;
            $data['page_limit']=$size;
            return $data;
        }
        $data['list'] =array();
        $data['count'] = 0;
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;

    }
    /**
     * 搜索
     */
    public function search2()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $sort=isset($this->requestData['sort'])?$this->requestData['sort']:'0';

        $lat  =isset($this->requestData['lat'])?trim($this->requestData['lat']): '23.13098';
        $lng =isset($this->requestData['lng'])?trim($this->requestData['lng']):  '113.403873';
        if(!isset($this->requestData['search']) || empty($this->requestData['search'])){
         return array("message"=>'请输入要搜索的内容');
         };
        $y = 5000 / 110852; //纬度的范围
        $x = 5000 / (111320*cos($lat)); //经度的范围
        $a = $lat-$y;
        $b = $lat+$y;
        $c = $lng-$x;
        $d = $lng+$x;
        $condition=' s.status=1';
        $condition.=' and  lat >='.$a.' and lat <= '.$b.' and  lng <='.$c.' and lng >= '.$d.'  ';
        $condition2 =' and shopname="'.$this->requestData['search'].'"';
        $list=db('shop')
            ->alias('s')
            ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount")
            ->join("category_shop c","c.id=s.cid")
            ->where($condition.$condition2)
            ->select();
        if($list) {
            $db_order=db("order");
            foreach ($list as $k => $val) {
                $radLat1 = deg2rad($lat);
                $radLat2 = deg2rad($val['lat']);
                $a = $radLat1 - $radLat2;
                $b = deg2rad($lng) - deg2rad($val['lng']);
                $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                $meter = $s * 6378137.0;
                $distant[] = $meter;
                if ($meter > 1000) {
                    $meter = number_format($meter / 1000, 2) . 'km';
                } else {
                    $meter = number_format($meter, 2) . 'm';
                }
                $list[$k]['distant'] = $meter;
                if ($val['headimage']) {
                    $list[$k]['headimage'] = IMG_PATH . $val['headimage'];
                }
                $where['shop_id'] = $val['id'];
                $where['status'] = '3';
                $where['finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                $list[$k]['ordernum'] = $db_order->where($where)->count();
                $num[]=$list[$k]['ordernum'];
                $ids[]= $val['id'];
                if ($val['discount']) {
                    $list[$k]['discount'] = unserialize($val['discount']);
                }
            }
            if($sort==0) {
                array_multisort($ids, SORT_ASC, $list);
            }elseif($sort==1){
                array_multisort($num, SORT_ASC, $list);
            }elseif($sort==2){
                array_multisort($distant, SORT_ASC, $list);
            }
            $shop = array_chunk($list, $size);
            $count = count($shop);
            if ($p > $count || $p < 1) return array("message" => '页码有误');
            $data['type'] =0;
            $data['list'] = $shop[$p - 1];
            $data['count'] = count($list);;
        }else {
            $dw['name'] = array("like", '%' . $this->requestData['search'] . '%');
            $goods = db('goods')
                ->field("id,shop_id,name,price,image")
                ->where($dw)
                ->select();
            $shop_ids = array_column($goods, 'shop_id');
            if ($shop_ids) {
                $condition3 = ' and s.id in (' . implode(",", $shop_ids) . ')';
                $list = db('shop')
                    ->alias('s')
                    ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname")
                    ->join("category_shop c", "c.id=s.cid")
                    ->where($condition . $condition3)
                    ->select();
                if ($list) {
                    $db_order = db("order");

                    foreach ($list as &$v) {
                        foreach ($goods as &$d) {
                            $where['o.shop_id'] = $d['shop_id'];
                            $where['o.status'] = '3';
                            $where['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                            $where['og.goods_id'] =$d['id'];
                            $d['order_num']= $db_order->alias("o")
                                ->join("order_goods og","og.order_id=o.id")
                                ->where($where)
                                ->count();
                            $d['image']= IMG_PATH. $d['image'];
                            if ($v['id'] == $d['shop_id']) {
                                $v['goods'][] = $d;
                            }
                        }
                        $or['shop_id'] = $v['id'];
                        $or['status'] = '3';
                        $or['finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                        $num[] = $db_order->where($or)->count();
                        if ($v['headimage']) {
                            $v['headimage'] = IMG_PATH . $v['headimage'];
                        }
                        $radLat1 = deg2rad($lat);
                        $radLat2 = deg2rad($v['lat']);
                        $a = $radLat1 - $radLat2;
                        $b = deg2rad($lng) - deg2rad($v['lng']);
                        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                        $meter = $s * 6378137.0;
                        $distant[] = $meter;
                        $ids[] = $v['id'];
                        if ($meter > 1000) {
                            $meter = number_format($meter / 1000, 2) . 'km';
                        } else {
                            $meter = number_format($meter, 2) . 'm';
                        }

                        $v['distant'] = $meter;
                    }
                    if($sort==0) {
                        array_multisort($ids, SORT_ASC, $list);
                    }elseif($sort==1){
                        array_multisort($num, SORT_ASC, $list);
                    }elseif($sort==2){
                        array_multisort($distant, SORT_ASC, $list);
                    }
                    $shop = array_chunk($list, $size);
                    $count = count($shop);
                    if ($p > $count || $p < 1) return array("message" => '页码有误');
                    $data['type'] = 1;
                    $data['list'] = $shop[$p - 1];
                    $data['count'] = count($list);;
                }
            }else{
                $data['type'] = 1;
                $data['list'] = array();
                $data['count'] = 0;
            }
        }
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }

    /**
     * 轮播图2
     */
    public function banner2(){
        $banner = db('banner2');
        $ban = $banner->select();
        foreach($ban as &$v){
            $v['img']=IMG_PATH.$v['img'];
            $shopid = db('shop')->where('shopname',$v['url'])->find();
            if($shopid){
                $v['url'] = $shopid['id'];
            }else{
                $v['url'] = 0;
            }
        }
        return $ban;
    }

    /**
     * 推荐2
     */
    public function activity2(){
        $banner = db('activity2');
        $ban = $banner->select();
        foreach($ban as &$v){
            $v['pic'] = IMG_PATH . $v['pic'];
        }
        return $ban;
    }

    /**
    *  首页
    */
    public function index(){
        //查询店铺
        $lat = isset($this->requestData['lat'])?trim($this->requestData['lat']):'23.041415';
        $lng = isset($this->requestData['lng'])?trim($this->requestData['lng']):'113.110804';
        if(empty($lat))$lat='23.13098';
        if(empty($lng))$lng = '113.403873';

        $url = 'http://api.map.baidu.com/geocoder/v2/?location='.$lat.','.$lng.'&output=json&pois=1&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';
        $res = file_get_contents($url);
        $res = json_decode($res,true);
//        var_dump($res);die;
//        var_dump($res['result']['addressComponent']);die;
        if (!empty($res) && $res['status'] == 0) {
            $city =$res['result']['addressComponent']['city'];
            $district =$res['result']['addressComponent']['district'];
            $town =$res['result']['addressComponent']['town'];
            $street =$res['result']['addressComponent']['street'];
        }else{
            $street = '';
            $city = '';
            $district = '';
            $town = '';
        }
        if(!isset($city)){
            $city = '佛山市';
        }

        $y = 5000 / 110852; //纬度的范围
        $x = 5000 / (111320*cos($lat)); //经度的范围
        $a = $lat-$y;
        $b = $lat+$y;
        $c = $lng-$x;
        $d = $lng+$x;

        $condition='status=1';
        $condition.=' and  lat >='.$a.' and lat <= '.$b.' and  lng <='.$c.' and lng >= '.$d.'  ';

        $shop_center = db('shop')->where($condition)->find();
        if(!empty($shop_center)){
            $sid = $shop_center['id'];
        }else{
            $shop['address']=['like','%'.$city.'%'];
            $shop['status']=1;
            $shop_home = db('shop')->where($shop)->find();
            if(!empty($shop_home)){
                $sid = $shop_home['id'];
            }else{
                $shop_home = db('shop')->where(['is_home'=>'1'])->find();
                $sid = $shop_home['id'];
                if(!$sid){
                    $shop_where['shopname']=['like','%搜付达%'];
                    $shop_home = db('shop')->where($shop_where)->find();
                }
                $sid = $shop_home['id'];
                if(!$sid) $sid=5;
            }
        }

        $result = [];
        $shop_id=trim($this->requestData['shop_id']);
        if(empty($shop_id)){
            $shop_id = $sid;
        }
//        var_dump($shop_id);die;
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $goods_cid=isset($this->requestData['goods_cid'])?$this->requestData['goods_cid']:0;

        if(empty($shop_id))return ['message'=>'请传shop_id为空!'];

        $shop = db('shop')->where(['id'=>$shop_id])->find();
        if(empty($shop))return ['message'=>'店铺shop_id参数有误！'];

        $category_goods = db('category_goods')->where(['shop_id'=>$shop_id,'status'=>'1'])->order('sort desc')->select();

        foreach ($category_goods as $key => &$value) {
            if(!empty($value['img'])){
                $value['img'] = IMG_PATH.$value['img'];
            }
        }

        $result['category_goods'] = $category_goods;

        if(empty($goods_cid)){
            if(!empty($category_goods)){
                $goods_cid = $category_goods[0]['id'];
            }
        }

        //banner查询
        $banner_list = db('banner_index')->where(['shop_id'=>$shop_id])->order('sort desc')->select();

        $banner_list_result = [];
        foreach ($banner_list as $key => &$value) {
            if(!empty($value['pic'])){
                $value['pic'] = IMG_PATH.$value['pic'];
            }

            if($value['position'] == '1'){
                $banner_list_result['top'][] = $value;
            }else{
                $banner_list_result['bottom'][] = $value;
            }
        }
        
        $result['banner_list_result'] = $banner_list_result;

        $activity_index = db('activity_index')->where(['shop_id'=>$shop_id])->order('sort desc')->limit('4')->select();

        foreach ($activity_index as $key => &$value) {
            $value['image'] = IMG_PATH.$value['image'];
        }

        $result['activity_index'] = $activity_index;

        //查询商品
        $goods_result = db('goods')->where(['shop_id'=>$shop_id,'cid'=>$goods_cid,'status'=>'1'])->page($page,'10')->select(); 

        foreach ($goods_result as $key => &$value) {
            if(!empty($value['image'])){
                $value['image'] = IMG_PATH.$value['image'];
            }

            $order_result = db('order')->alias('o')
                ->join('order_goods og','og.order_id=o.id')
                ->join('member m','m.id=o.user_id')
                ->where("og.goods_id={$value['id']} and m.nickname != ''")
                ->group('og.order_id')
                ->order('o.id desc')
                ->limit(10)
                ->field('m.nickname,m.headimage')
                ->select();
            //$user_ids = explode(',',$order_result);

//            if(!empty($user_ids)) {
//                $where_member['id'] = ['in',$user_ids];
//                $where_member['nickname'] = ['<>',''];
//                $order_member = db('member')->where($where_member)->field("nickname,headimage")->select();
//            }else{
//                $order_member = [];
//            }
            $value['order_member'] = $order_result;
            $value['option'] = db('goods_option')->where("goodsid=" . $value['id'])->select();
        }

        if($shop['discount']) {
            $result['shop_discount'] = unserialize($shop['discount']);
        }

        $result['full_distribution'] = $shop['full_distribution'];

        $result['goods_result'] = $goods_result;

        //查询所有的店铺
        $arr[] = $street;
        $arr[] = $town;
        $arr[] = $district;
        $arr[] = $city?$city:'佛山市1';

        foreach($arr as $k=>$v){
            if(!empty($arr[$k])){
                $shop_condition['city|county|street|address']=['like','%'.$arr[$k].'%'];
                $shop_condition['status']=1;
                $shop_result = db('shop')->where($shop_condition)->select();
//                $shopsql = db('shop')->getLastSql();
            }
            if(isset($shop_result) && !empty($shop_result))break;
        }
//die;
        if(isset($shop_result)){
            $result['shop_result'] = $shop_result;
            if(is_array($shop_result)){
                foreach ($result['shop_result'] as $key => &$value) {
                    $discount = unserialize($value['discount']);
                    if($discount == false){
                        $value['discount'] = [];
                    }else{
                        $value['discount'] = $discount;
                    }

                    $open_time = unserialize($value['open_time']);
                    if($open_time == false){
                        $value['open_time'] = [];
                    }else{
                        $value['open_time'] = $open_time;
                    }

                    $updateimages = unserialize($value['updateimages']);
                    if($open_time == false){
                        $value['updateimages'] = [];
                    }else{
                        $value['updateimages'] = $updateimages;
                    }

                    $value['headimage'] = IMG_PATH.$value['headimage'];
                }
            }
        }



        $result['shopid'] = $shop_id;
        return $result;
    }

    public function getshop(){
        //查询店铺
        $lat = isset($this->requestData['lat'])?trim($this->requestData['lat']):'23.041415';
        $lng = isset($this->requestData['lng'])?trim($this->requestData['lng']):'113.110804';
        if(empty($lat))$lat='23.13098';
        if(empty($lng))$lng = '113.403873';
// var_dump($lat);
// var_dump($lng);
        $url = 'http://api.map.baidu.com/geocoder/v2/?location='.$lat.','.$lng.'&output=json&pois=1&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';
        $res = file_get_contents($url);
        $res = json_decode($res,true);
//        var_dump($res);die;
        // var_dump($res['result']['addressComponent']);die;
        if (!empty($res) && $res['status'] == 0) {
            $city =$res['result']['addressComponent']['city'];
            // $district =$res['result']['addressComponent']['district'];
            // $town =$res['result']['addressComponent']['town'];
            // $street =$res['result']['addressComponent']['street'];
            $district =$res['result']['addressComponent']['district'];
            $town =$res['result']['addressComponent']['town'];
            $street =$res['result']['addressComponent']['street'];
        }
        if(!isset($city)){
            $city = '佛山市';
        }
        if(!isset($district)){
            $district = '';
        }
        if(!isset($town)){
            $town = '';
        }
        if(!isset($street)){
            $street = '';
        }
        //查询所有的店铺
        $arr[] = $street;
        $arr[] = $town;
        $arr[] = $district;
        $arr[] = $city?$city:'佛山市';

        foreach($arr as $k=>$v){
            if(!empty($arr[$k])){
                $shop_condition['city|county|street|address']=['like','%'.$arr[$k].'%'];
                $shop_condition['status']=1;
                $shop_result = db('shop')->where($shop_condition)->select();
//                $shopsql = db('shop')->getLastSql();
            }
            if(isset($shop_result) && !empty($shop_result))break;
        }
//die;
        if(isset($shop_result)){
            if(is_array($shop_result)){
                foreach ($shop_result as $key => &$value) {
                    $discount = unserialize($value['discount']);
                    if($discount == false){
                        $value['discount'] = [];
                    }else{
                        $value['discount'] = $discount;
                    }

                    $open_time = unserialize($value['open_time']);
                    if($open_time == false){
                        $value['open_time'] = [];
                    }else{
                        $value['open_time'] = $open_time;
                    }

                    $updateimages = unserialize($value['updateimages']);
                    if($open_time == false){
                        $value['updateimages'] = [];
                    }else{
                        $value['updateimages'] = $updateimages;
                    }

                    $value['headimage'] = IMG_PATH.$value['headimage'];
                }
            }
        }
        $result['shop_result'] = $shop_result;
        return $result;

    }
    public function getcity()
    {
        $city = db('shop')->distinct(true)->field('city')->where('isid =1')->column('city');

//        $where['level'] = 1;
//        $area = db('one_area')->order('num')->select();
//        foreach($area as $key=>&$val)
//        {
//            $where['id'] = ['in',$val['son']];
//            $val['address'] = db('one_city')->where($where)->select();
//        }
        $address = db('one_city')->where('level = 1')->select();
        foreach($address as $key=>&$val)
        {
            $cname = $val['name'];
            if(array_search($cname,$city) !== false){
                $val['isopen'] = 1;
            }else{
                $val['isopen'] = 0;
            }
            $child = db('one_city')->where(['parent_id'=>$val['id']])->select();
//            $val['child'] = db('one_city')->where(['parent_id'=>$val['id']])->select();
            foreach($child as $kk=>$vv)
            {
                $cityname = $child[$kk]['name'];
                if(array_search($cityname,$city) !== false){
                    $child[$kk]['isopen'] = 1;
                }else{
                    $child[$kk]['isopen'] = 0;
                }
            }
            $val['child'] = $child;
        }
        $result['city'] = $address;
        return $result;
    }
}